package com.wuzhun.wxmp.controller.admin;


import com.wuzhun.wxmp.annotation.LoginRequired;
import com.wuzhun.wxmp.annotation.PageLoginRequired;
import com.wuzhun.wxmp.common.Result;
import com.wuzhun.wxmp.common.ResultCode;
import com.wuzhun.wxmp.common.ServiceException;
import com.wuzhun.wxmp.constant.CommonConstant;
import com.wuzhun.wxmp.controller.BaseController;
import com.wuzhun.wxmp.model.dto.TokenDTO;
import com.wuzhun.wxmp.model.dto.WechatDTO;
import com.wuzhun.wxmp.model.dto.admin.AdminUserDTO;
import com.wuzhun.wxmp.model.dto.admin.AdminUserResultDTO;
import com.wuzhun.wxmp.model.entity.AdminUser;
import com.wuzhun.wxmp.service.IAdminUserService;
import com.wuzhun.wxmp.service.ICaptchaServiceService;
import com.wuzhun.wxmp.service.ITokenService;
import com.wuzhun.wxmp.service.IWechatService;
import com.wuzhun.wxmp.util.CookieUtil;
import com.wuzhun.wxmp.util.IpUtil;
import com.wuzhun.wxmp.util.StringUtil;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author renbaolin
 * @since 2022-12-05
 */
@Controller
@RequestMapping("/admin/user")
public class AdminUserController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AdminUserController.class);

    @Value("${wuzhun.domain}")
    private String domain;

    @Resource
    private IAdminUserService userService;

    @Resource
    private ITokenService tokenService;

    @Resource
    private ICaptchaServiceService captchaServiceService;

    @Resource
    private IWechatService wechatService;

    @GetMapping(value = "/login")
    @PageLoginRequired
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
        String token = CookieUtil.getCookie(request, "token");
        if (tokenService.verifyToken(token)) {
            try {
                response.sendRedirect(domain + "/admin/main");
            } catch (IOException e) {
                LOGGER.error("AdminUserController.login error ", e);
            }
            return null;
        } else {
            return commonView(new ModelAndView(), "admin/user/login");
        }
    }

    @PostMapping(value = "login")
    @ApiOperation("用户登录接口")
    @ResponseBody
    @LoginRequired
    public Result doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("imageCode") String imageCode,
                          HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) {
        captchaServiceService.verifyImageCode(httpServletRequest, imageCode, true);
        AdminUserDTO adminUserDTO = userService.queryUserAndCheckPassword(IpUtil.getIpAddress(httpServletRequest), username, password);
        Integer uid = adminUserDTO.getUid();
        TokenDTO tokenDTO = tokenService.queryTokenByUid(uid);
        if (tokenDTO == null || tokenDTO.getExpireTime().getTime() < System.currentTimeMillis()) {
            tokenDTO = tokenService.generateAndInsert(uid, IpUtil.getIpAddress(httpServletRequest));
        }
        AdminUserResultDTO adminUserResultDTO = new AdminUserResultDTO();
        adminUserResultDTO.setAdminUser(adminUserDTO);
        adminUserResultDTO.setToken(tokenDTO);
        int expireTime = (int) ((tokenDTO.getExpireTime().getTime() - System.currentTimeMillis()) / 1000);
        CookieUtil.setCookie(httpServletResponse, CommonConstant.TOKEN_KEY, tokenDTO.getToken(), expireTime);
        CookieUtil.setCookie(httpServletResponse, "username", adminUserDTO.getUsername(), expireTime);
        CookieUtil.setCookie(httpServletResponse, CommonConstant.LAST_ACTIVE_TIME_KEY, String.valueOf(System.currentTimeMillis()), CommonConstant.THIRTY_MINUTE_MILLS);
        return new Result(adminUserResultDTO);
    }

    @GetMapping(value = "/edit-password")
    @PageLoginRequired
    public ModelAndView editPassword() {
        return commonView(new ModelAndView(), "admin/user/edit-password");
    }

    @PostMapping(value = "/edit-password")
    @ApiOperation("用户修改接口")
    @LoginRequired
    @ResponseBody
    public Result editPassword(@RequestParam("oldPassword") String oldPassword,
                                @RequestParam("newPassword") String newPassword,
                                @RequestParam("repeatPassword") String repeatPassword,
                                HttpServletRequest request) {
        Integer uid = tokenService.queryUidByToken(CookieUtil.getCookie(request, CommonConstant.TOKEN_KEY));
        return new Result(userService.editPassword(uid, oldPassword, newPassword, repeatPassword));
    }

    @GetMapping(value = "/logout")
    @PageLoginRequired
    public void logout(HttpServletResponse response, HttpServletRequest request) {
        try {
            CookieUtil.deleteCookie(response, CommonConstant.USERNAME_KEY);
            CookieUtil.deleteCookie(response, CommonConstant.TOKEN_KEY);
            response.sendRedirect(domain + "/admin/user/login");
        } catch (IOException e) {
            LOGGER.error("AdminUserController.logout error ", e);
        }
    }

    /**
     * 验证码
     *
     * @param request
     * @param response
     */
    @GetMapping("/letter-number")
    public void happyCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(140, 40, 4, request, response);
    }
}
